import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import { useState, useEffect } from 'react';

const getBase64 = (img:any, callback:any) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file:any) => {
    console.log('beforeUpload',file);
};

const Uploader = (props:any) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');

  let {getUploadImhUrl,categoryImgurl} = props
  
  useEffect(() => {
    setImageUrl(categoryImgurl)
  },[categoryImgurl])

  const handleChange = (info:any) => {

      if (info.file.status === 'uploading') {
          setLoading(true);
          return;
        }
        
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            // console.log('UploadDone',info.file.originFileObj);
            getUploadImhUrl(info.file.response.headimgurl)

            getBase64(info.file.originFileObj, (url:any) => {
                setLoading(false);
                setImageUrl(url);
            });

        }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传类目图片
      </div>
    </div>
  );

  return (
    <Upload
      name="headimgurl"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="/api/students/uploadStuAvatar"
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

export default Uploader;